/*
 * @Description  :
 * @Author       : YiDing Xue
 * @Date         : 2023-02-27
 * @LastEditors  : YiDing Xue
 * @LastEditTime : 2023-03-13
 */

import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import { setupRouterGuard } from './guard'
import { basicRoutes, NOT_FOUND_ROUTE } from './routes/index'
const isHash = import.meta.env.VITE_USE_HASH === 'true'
export const router = createRouter({
  history: isHash ? createWebHashHistory('/') : createWebHistory(),
  routes: basicRoutes,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

export const setupRouter = async app => {
  setupRouterGuard(router)
  router.addRoute(NOT_FOUND_ROUTE)
  app.use(router)
}

export const resetRouter = async () => {
  const basicRouteNames = getRouteNames(basicRoutes)
  router.getRoutes().forEach(route => {
    const name = route.name
    if (!basicRouteNames.includes(name)) {
      router.removeRoute(name)
    }
  })
  router.push({ name: 'home' })
}

export const getRouteNames = routes => {
  return routes.map(route => getRouteName(route)).flat(1)
}

const getRouteName = route => {
  const names = [route.name]
  if (route.children && route.children.length) {
    names.push(...route.children.map(item => getRouteName(item)).flat(1))
  }
  return names
}
